// 验证提交表单的数据
import ElementUI from 'element-ui';

async function checkTemplateList(templateList) {
  let checkAll = true; //是否全部验证通过
  for (let i = 0; i < templateList.length;) {
    let result = await checkItem(templateList[i], i);
    if (result == "break") {
      checkAll = false;
      break;
    } else {
      i++;
    }
  }
  if (checkAll) {
    // 检测必填字段是否拥有(uIdCard&&uName&&uTel||uEmail)
    checkAll = await checkMustField(templateList);
  }
  if (checkAll) {
    let subData = {
      componenList: [],
    }
    for (let i = 0; i < templateList.length; i++) {
      let obj = {
        attribute: templateList[i].attribute,
        componentName: templateList[i].componentName,
      }
      subData.componenList.push(obj);
    }
    return subData;
  }

}

function checkItem(item, index) {
  return new Promise((resolve, reject) => {
    // 公共验证
    if (!item.attribute.filedCode) {
      ElementUI.Message.warning(`请选择第${index+1}个字段的字段编码`);
      resolve("break");
    }

    if (!item.attribute.titName) {
      ElementUI.Message.warning(`请输入第${index+1}个字段的标题名称`);
      resolve("break");
    }

    // stringTem组件验证
    if (item.componentName == "stringTem") {
      if (!item.attribute.maxLength) {
        ElementUI.Message.warning(`请输入第${index+1}个字段的最大字符长度`);
        resolve("break");
      }
    }

    // numberTem组件验证
    if (item.componentName == "numberTem") {
      if (item.attribute.minValue === "") {
        ElementUI.Message.warning(`请输入第${index+1}个字段的最小数值`);
        resolve("break");
      }
      if (item.attribute.maxValue === "") {
        ElementUI.Message.warning(`请输入第${index+1}个字段的最大数值`);
        resolve("break");
      }
    }

    // moreSelectTem组件验证
    if (item.componentName == "moreSelectTem") {
      if (item.attribute.selectList.length == 0) {
        ElementUI.Message.warning(`请添加第${index+1}个字段的菜单选项`);
        resolve("break");
      }

    }
    resolve("ok");
  });
}
// 检测必填字段是否拥有(U_ID_CARD&&uName&&uTel||uEmail)
function checkMustField(templateList) {
  return new Promise((resolve, reject) => {
    let uIdCard = false;
    let uName = false;
    let uTel = false;
    let uEmail = false;
    for (let i = 0; i < templateList.length; i++) {
      if (templateList[i].attribute.filedCode == "uIdCard") {
        uIdCard = true;
      }
      if (templateList[i].attribute.filedCode == "uName") {
        uName = true;
      }
      if (templateList[i].attribute.filedCode == "uTel") {
        uTel = true;
      }
      if (templateList[i].attribute.filedCode == "uEmail") {
        uEmail = true;
      }
    }
    if (uName && uTel) {
      resolve(true);
    } else {
      // if (!uIdCard) {
      //   ElementUI.Message.warning(`请添加使用人证件号字段编码`);
      // } else 

      if (!uName) {
        ElementUI.Message.warning(`请添加使用人姓名`);
      } else {
        ElementUI.Message.warning(`请添加使用人电话`);
      }
      resolve(false);
    }

  });
}

export {
  checkTemplateList
}
